package com.ikun.service.impl;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ikun.dao.AttendancesDao;
import com.ikun.entity.Attendances;
import com.ikun.service.AttendancesService;
import com.ikun.util.DateUtil;
import com.ikun.util.Result;

import jakarta.annotation.Resource;

/**
 * 考勤表(Attendances)表服务实现类
 *
 * @author Li
 * @since 2025-03-26 10:52:46
 */
@Service
public class AttendancesServiceImpl implements AttendancesService {
    @Resource
    private AttendancesDao attendancesDao;

    @Override
    @Transactional // 确保事务性
    public Result clock_in(Integer staffId, LocalTime currentTime) {
        LocalTime eightForty = LocalTime.of(8, 40);
        LocalTime twelve = LocalTime.of(18, 0);

        if (currentTime.isAfter(twelve)) {
            return Result.error("超过12:00，无法打卡");
        }

        int status;
        String attendanceStatus;
        if (currentTime.isBefore(eightForty)) {
            status = 1;
            attendanceStatus = "牛马来了";
        } else {
            status = 2;
            attendanceStatus = "牛马迟到了";
        }

        Attendances attendances = new Attendances();
        attendances.setStaffId(staffId);
        // 设置记录日期
        attendances.setRecordDate(LocalDate.now());
        // 组合当前日期和时间，创建 java.sql.Timestamp 对象
        LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), currentTime);
        attendances.setClockIn(Timestamp.valueOf(dateTime));
        attendances.setStatus(status);

        System.out.println("attendances = " + attendances);
        if (attendancesDao.findAttendancesByStaffIdAndRecordDate(staffId,
            DateUtil.format(new java.util.Date(), "yyyy-MM-dd")) == null) {
            // 当天没有打卡记录，插入新的打卡记录
            attendancesDao.insert(attendances);
        }
        //
        String staffName = attendancesDao.getStaffNameById(staffId);

        Map<String, Object> data = new HashMap<>();
        data.put("attendance_id", attendances.getAttendanceId());
        data.put("name", staffName);
        data.put("clock_in_time", attendances.getClockIn());
        data.put("status", attendanceStatus);
        return Result.success("打卡成功", data);
    }

    @Override
    public Result clock_out(Integer staffId, LocalTime currentTime) {
        LocalDate recordDate = LocalDate.now();
        LocalTime eighteenThirty = LocalTime.of(18, 30);
        int status;
        String attendanceStatus;
        if (currentTime.isBefore(eighteenThirty)) {
            status = 3;
            attendanceStatus = "牛马早退了";
        } else {
            status = 4;
            attendanceStatus = "牛马明天继续加油";
        }
        java.sql.Date date = java.sql.Date.valueOf(LocalDate.now());
        Integer attendanceId = attendancesDao.getLatestAttendanceId(staffId, recordDate);

        if (attendanceId == null) {
            return Result.error("未找到当天的上班打卡记录，无法进行下班打卡");
        }
        Timestamp clockOut = Timestamp.valueOf(LocalDateTime.of(LocalDate.now(), currentTime));
        attendancesDao.updateClockOut(attendanceId, clockOut, status);

        String staffName = attendancesDao.getStaffNameById(staffId);
        Map<String, Object> data = new HashMap<>();
        data.put("attendance_id", attendanceId);
        data.put("staff_name", staffName);
        data.put("clock_out_time", clockOut);
        data.put("attendance_status", attendanceStatus);
        return Result.success("打卡成功", data);
    }

    @Override
    public Result insertStatus(Integer staffId, LocalDate recordDate, Integer status) {
        Attendances attendances = new Attendances();
        attendances.setStaffId(staffId);
        attendances.setRecordDate(recordDate);
        attendances.setStatus(status);
        int i = attendancesDao.insert(attendances);
        return i > 0 ? Result.success("请假成功", attendances) : Result.error("请假失败");
    }

    @Override
    public Result<List<Attendances>> getAttendanceRecords(Map<String, Object> params) {
        List<Attendances> records = attendancesDao.getAttendanceRecords(params);
        return Result.success(records);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param attendanceId 主键
     * @return 实例对象
     */

    @Override
    public Attendances queryById(Integer attendanceId) {
        return attendancesDao.queryById(attendanceId);
    }

    /**
     * 新增数据
     *
     * @param attendances 实例对象
     * @return 实例对象
     */
    @Override
    public Attendances insert(Attendances attendances) {
        this.attendancesDao.insert(attendances);
        return attendances;
    }

    /**
     * 修改数据
     *
     * @param attendances 实例对象
     * @return 实例对象
     */
    @Override
    public Attendances update(Attendances attendances) {
        this.attendancesDao.update(attendances);
        return this.queryById(attendances.getAttendanceId());
    }

    /**
     * 通过主键删除数据
     *
     * @param attendanceId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer attendanceId) {
        return this.attendancesDao.deleteById(attendanceId) > 0;
    }

    @Override
    public int calculateAttendanceDays(String formattedYearMonth, String manageId) {
        return attendancesDao.calculateAttendanceDays(formattedYearMonth, manageId);
    }

    @Override
    public List<Attendances> findAllStuffAttendances(String datePart, String namePart) {
        return attendancesDao.findAllStuffAttendances(datePart, namePart);
    }

    @Override
    public List<Attendances> getAllAttendance(Integer staffId) {
        return attendancesDao.getAllAttendance(staffId);
    }

    @Override
    public List<Attendances> allAttendances(String recordDate, String startTime, String endTime) {
        return attendancesDao.allAttendances(recordDate, startTime, endTime);
    }
}
